<template>
  <div>
    <el-form
      :model="userForm"
      :rules="userRules"
      ref="addFormRef"
      label-width="100px"
    >
      <el-form-item label="登录账号" prop="account">
        <el-input v-model="userForm.account"></el-input>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="userForm.name"></el-input>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="userForm.type" placeholder="请选择">
          <el-option
            v-for="item in roles"
            :key="item.key"
            :label="item.title"
            :value="item.key"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <!-- 底部区域,点击取消或者确定的时候隐藏对话框 -->
    <span slot="footer" class="block text-center">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="addUser">确 定</el-button>
    </span>
  </div>
</template>

<script>
import { isEmail, isTelCode } from "@/common/util/validate.js";

export default {
  props: ["confirm", "cancel", "roles"],
  data() {
    // 验证邮箱的校验规则
    var checkEmail = (userRules, value, cb) => {
      if (isEmail(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    // 验证手机号的规则
    var checkMobile = (userRules, value, cb) => {
      if (isTelCode(value)) {
        return cb();
      }
      cb(new Error("请输入合法的电话号码"));
    };
    return {
      userForm: {
        account: "",
        name: "",
        type: "",
      },
      userRules: {
        account: [
          { required: true, message: "请输入登录账号", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        name: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 3,
            max: 15,
            message: "长度在 3 到 15 个字符",
            trigger: "blur",
          },
        ],
        type: [{ required: true, message: "请选择用户类型", trigger: "blur" }],
      },
    };
  },
  methods: {
    addUser() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return this.$message.error("填写信息错误或不合规则");
        this.confirm(this.userForm);
      });
    },
    resetFields() {
      this.$refs.addFormRef.resetFields();
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form {
  width: 70%;
  margin: 0 auto;
}
.el-select >>> .el-input {
  width: 320px;
}
</style>
